// pages/category/index.js
import { request } from "../../request/index";
import regeneratorRuntime from "../../lib/runtime/runtime";
Page({
  data: {
    currentIndex: 0,
    leftMenuList: [],
    rightContent: [],
    scrollTop: 0
  },
  cates: [],
  onLoad: function(options) {
    const Cates = wx.getStorageSync("cates");
    if (!Cates) {
      this.getCates();
    } else {
      if (Date.now() - Cates.time > 5000 * 100) {
        this.getCates();
      } else {
        console.log("可以使用旧数据");
        this.cates = Cates.data;
        // console.log(this.cates);
        let leftMenuList = this.cates.map(v => v.cat_name);
        let rightContent = this.cates[0].children;
        this.setData({
          leftMenuList,
          rightContent
        });
      }
    }
  },
  async getCates() {
    // request({
    //   url: "/categories"
    // }).then(result => {
    //   this.cates = result.data.message;
    //   wx.setStorageSync("cates", { time: Date.now(), data: this.cates });
    //   // console.log(this.cates);
    //   let leftMenuList = this.cates.map(v => v.cat_name);
    //   let rightContent = this.cates[0].children;
    //   this.setData({
    //     leftMenuList,
    //     rightContent
    //   });
    // });
    const result = await request({ url: "/categories" });
    this.cates = result;
    wx.setStorageSync("cates", { time: Date.now(), data: this.cates });
    let leftMenuList = this.cates.map(v => v.cat_name);
    let rightContent = this.cates[0].children;
    this.setData({
      leftMenuList,
      rightContent
    });
  },
  changeMenuColor(e) {
    // 两种方式
    // let newCurrentIndex= e.target.dataset.index;
    // this.setData({
    //   currentIndex:newCurrentIndex
    // })
    // console.log(newCurrentIndex)
    const { index } = e.currentTarget.dataset;
    let rightContent = this.cates[index].children;
    console.log(rightContent);
    
    this.setData({
      currentIndex: index,
      rightContent,
      scrollTop: 0
    });
  }
});
